package util.loaders;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;


/**
 * Loads resources from an external jar in the filesystem.
 * 
 * @author Jason
 *
 */
public class ExternalJarLoader extends DataLoader{

	protected final ZipFile zip;
	
	public ExternalJarLoader(String jarPath){
		this(new File(jarPath));
	}
	
	public ExternalJarLoader(File jarFile){
		if(jarFile == null || jarFile.isFile() == false)
			throw new RuntimeException("The file specified does not exist!"+
					" File = "+jarFile);
		try{
			zip = new ZipFile(jarFile);
		}
		catch(Exception e){
			throw new RuntimeException("Failed to create zip file.");
		}
	}
	
	@Override
	public InputStream load(String dataName) throws IOException{
		Enumeration<? extends ZipEntry> entries = zip.entries();
		while(entries.hasMoreElements()){
			ZipEntry entry = entries.nextElement();
			if(entry.getName().equals(dataName)){
				InputStream is = zip.getInputStream(entry);
				return is;
			}
		}
		return null;
	}

}
